import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
	{
		path: '/',
		redirect: '/applyFor',
	},
	{
		path: '/home',
		name: 'home',
		component: () => import('@/views/home/index.page.vue'),
	},
	{
		path: '/applyFor',
		name: 'applyFor',
		component: () => import('@/views/applyFor/index.page.vue'),
	},
	{
		path: '/login',
		name: 'login',
		component: () => import('@/views/login/index.page.vue'),
	},
	{
		path: '/back',
		name: 'back',
		component: () => import('@/views/search/index.page.vue'),
	},
	{
		// 匹配所有路径  vue2使用*   vue3使用/:pathMatch(.*)*或/:pathMatch(.*)或/:catchAll(.*)
		path: '/:pathMatch(.*)',
		component: () => import('@/views/404/index.page.vue'),
	},
]

const router = createRouter({
	history: createWebHistory(),
	routes,
})

router.beforeEach((to, from, next) => {
	if(!['/login','/back'].includes(to.path)){
		next()
		return
	}
	const token = localStorage.getItem('token')
	if (!token) {
		if (to.path == '/login') {
			next()
		} else {
			router.push('login')
		}
	} else {
		next()
	}
})

export default router
